<?php
// +----------------------------------------------------------------------
// | 版权所有 2016~2017 路人甲乙科技有限公司 [ http://www.lurenjiayi.com ]
// +----------------------------------------------------------------------
// | 官方网站: http://lurenjiayi.com
// +----------------------------------------------------------------------
// | 开源协议 ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | @author 张继立 <404851763@qq.com>
// +----------------------------------------------------------------------

namespace app\money\home;
use  app\member\home\Common;
use  app\money\model\Recharge as ChargeModel;
use think\Db;
use app\money\model\Record;

/**
 * 前台首页控制器
 * @package app\money\home
 */
class Recharge extends Common
{
    protected $debaoNotice_url="";
    protected $debaoReturn_url="";
    protected $debao_url="";
    protected function _initialize()
    {
        parent::_initialize();
        $this->assign('active', 'charge');
        //debao
        $this->debao_url = "https://pay.yuanruic.com/gateway?input_charset=UTF-8"; //得宝跳转地址
        $this->debaoReturn_url = http() . $_SERVER['HTTP_HOST'] . "/member.html";//返回商户前台同步
        $this->debaoNotice_url = http() . $_SERVER['HTTP_HOST'] . "/index/index/payDebaoNotice";//返回商户后台异步
    }
   /**
    * 首页
    * @return [type] [description]
    */
    public function index()
    {
        //$this->redirect('/money/recharge/online.html');
    	$money = \app\money\model\Money::getMoney(MID);
    	$account=Db::name("admin_bank")->where(['status'=>1])->select();
    	$this->assign('offline',config('web_site_account'));
    	$this->assign('online_recharge_switch',config('online_recharge_switch'));
    	$this->assign('service_time',config('web_site_service_time'));
    	$this->assign('service_telephone',config('web_site_telephone'));
    	$this->assign('account',$account);
    	$this->assign('money', $money);
        return $this->fetch();
    }

    public function online() {
        $money = \app\money\model\Money::getMoney(MID);
    	$account=Db::name("admin_bank")->where(['status'=>1])->select();
    	$this->assign('offline',config('web_site_account'));
    	$this->assign('online_recharge_switch',config('online_recharge_switch'));
    	$this->assign('service_time',config('web_site_service_time'));
    	$this->assign('service_telephone',config('web_site_telephone'));
    	$this->assign('account',$account);
    	$this->assign('money', $money);
        return $this->fetch();
    }
  
    public function doCharge()
    {
        if($this->request->isPost())
        {
            $data = $this->request->post();
            if($data['charge_type']=="transfer"){
                $result = $this->validate($data, "Recharge.newdata");
                if(true !== $result){
                    $this->error($result);
                }
            }else{
                $result = $this->validate($data, "Recharge.online");
                if(true !== $result){
                    $this->error($result);
                }
            }

            $money = $data['money'];
            if($money <= 0){
                $this->error('充值金额必须大于0');
            }
            $data['mid'] = MID;
            $type = $data['charge_type']; // transfer 线下转账支付
            $receipt_img = input('receipt_img');
            $charge_type_id = $data['charge_type_id'];
            $transfer = $data['transfer'];
            $line_bank = '时间：'.date('Y-m-d',time());
            $order_no = ChargeModel::saveData($money, MID, $type, $line_bank,$receipt_img,$charge_type_id,$transfer);
            if($order_no){
                if($type == 'transfer'){
                    $var = Db::name('member')->where('id',MID)->value('mobile');
                    $contentarr  = getconfigSms_status(['name'=>'stock_offline']);
                    $content = str_replace(array("#var#","#amount#"),array($var,$money), $contentarr['value']);
                    if($contentarr['status']==1){
                    sendsms_mandao('', $content, '');
                    }
                    $this->success('充值已提交，请耐心等待审核', url('@member/index/index'));
                }else{
					$this->success('敬请期待！');
					exit();
                    switch ($type){
                        case "debao":
                            //$this->debao_pay($order_no,$money);
                     		//$this->hj_pay($order_no,$money);
                            break;
						case "huanqiu":
                     		//$this->hq_pay($order_no,$money,$data['bankCode']);
                            break;
						case "lsjjh":
                     		//$this->lsjjh_pay($order_no,$money,$data['bankCode']);
                            break;
						case "dspay":
                     		//$this->ds_pay($order_no,$money,$data['bankCode'],$data['bankcardid'],$data['bankfullname'],$data['bankidc'],$data['bankmobile']);
                            break;
						case "hjpay":
							//$this->hj_pay($order_no,$money,$data['bankCode']);
                            break;
						case "klpay":
                     		//$this->kl_pay($order_no,$money,$data['bankCode']);
                            break;
						case "xfzhpay":
                     		//$this->xfzh_pay($order_no,$money,$data['bankCode']);
                            break;
						default:
							$this->error('错误的支付方式');
                    }
                }
            }else{
                $this->error('充值错误');
            }

        }
    }
	
	public function xfzh_pay($order_no,$money, $bankCode){
		$pay_url = "http://103.193.243.85/newpay/api/v2/quick/order/pay";
		$notifyurl = http() . $_SERVER['HTTP_HOST'] . '/index/index/xfzhpayNotice';	//异步回调通知地址
		$callbackurl = http() . $_SERVER['HTTP_HOST'] . '/wap/member/index';
		
		$appid = "19553068";
		$key = "6654d08ab00c41e18eab8697f28ab7b2";
		$data = array(
			"appId" => $appid, 
			"bankCode"=>$bankCode,
			"version" => "V1.0", 
			"charset" => "11", 
			"requestTime" => date("YmdHis",time()),
			"clientIp" => $this->getClientIP(), 
			"signType" => "01", 
			"userCode" => MID, 
			"orderCode" => $order_no, 
			"orderTime" => date("YmdHis",time()),
			"currency" => "CNY", 
			"amount" => ceil($money*100), 
			"subject" => "recharge", 
			"body" => "recharge", 
			"channelType" => "2", 
			"returnUrl" => $callbackurl, 
			"notifyUrl" => $notifyurl
		);
		ksort($data);
		reset($data);
		$signstr = "";
		foreach ($data as $k => $v) {
			//if($k!="bankCode"){
				$signstr .= $k . "=" . $v . "&";
			//}
		}
		$signstr .= 'key=' . $key;
		$sign = strtoupper(md5($signstr));
		$data['sign'] = $sign;	//签名
		
		$headers = array(
			"Content-type: application/json;charset='utf-8'", 
			"Accept: application/json", 
			"Cache-Control: no-cache", 
			"Pragma: no-cache", 
		);
        $postUrl = $url;
        $curlPost = $post_data;
        $ch = curl_init();//初始化curl
        curl_setopt($ch, CURLOPT_URL,$pay_url);//抓取指定网页
        curl_setopt($ch, CURLOPT_POST, 1);//post提交方式
        curl_setopt($ch, CURLOPT_HEADER, 0);//是否输出头
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);//设置header
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
        $redata = curl_exec($ch);//运行curl
        curl_close($ch);
        
		if(!empty($redata)){
			$re = json_decode($redata,true);
			if($re['code']==="000000"){
				exit($re['data']['payHtml']);
			}else{
				exit($re['msg']);
			}
		}else{
			exit("server response nothing!");
		}
		
	}
	
	public function kl_pay($order_no,$money , $bankCode){
		$pay_url = "http://www.vip12358.com/Pay_Index.html";
		$notifyurl = http() . $_SERVER['HTTP_HOST'] . '/index/index/klpayNotice';	//异步回调通知地址
		$callbackurl = http() . $_SERVER['HTTP_HOST'] . '/wap/member/index';
		
		$pay_memberid = "10110";
		$pay_apikey = "crizgr9kpd92ch5vdmksk9acw4x867dp";
		
		$data = array(
			"pay_memberid" => $pay_memberid, 
			"pay_orderid" => $order_no, 
			"pay_amount" => sprintf("%.2f", $money),
			"pay_applydate" => date("Y-m-d H:i:s"), 
			"pay_bankcode" => $bankCode, 
			"pay_notifyurl" => $notifyurl, 
			"pay_callbackurl" => $callbackurl
		);
		ksort($data);
		reset($data);
		$signstr = "";
		foreach ($data as $k => $v) {
			$signstr .= $k . "=" . $v . "&";
		}
		$signstr .= 'key=' . $pay_apikey;
		$sign = strtolower(md5($signstr));
		if($bankCode=="916"){
			$data['pay_banktype'] = "CCB";
		}
		$data['pay_attach'] = 'recharge';	//备注信息
		$data['pay_md5sign'] = $sign;	//签名
		$data['pay_returntype'] = "text";
		echo "<form id=\"sjsubmit\" method=\"post\" action=\"".$pay_url."\">";
		foreach ($data as $key => $val) {
			echo '<input type="hidden" name="' . $key . '" value="' . $val . '">';
		}
        echo "</form>";
		echo "<script>document.forms['sjsubmit'].submit();</script>";
	}
	
	public function hj_pay($order_no,$money , $bankCode){
		$hjurl = "http://api.huijie9.com/payment/";
		$secretkey = "568ff08fbf61173c0f194d076670981a";
		$post_data['mer_id'] = '1560';	//您的商户ID
		$post_data['order_id'] = $order_no;	//订单号
		$post_data['amount'] = $money;	//订单金额。单位：元
		$post_data['bank_code'] = $bankCode;		//银行编码
		$post_data['notify_url'] = http() . $_SERVER['HTTP_HOST'] . '/index/index/hjpayNotice';	//异步回调通知地址

		ksort($post_data);
		reset($post_data);
		$signstr = "";
		foreach ($post_data as $k => $v) {
			$signstr .= $k . "=" . $v . "&";
		}
		$signstr .= 'key=' . $secretkey;
		$sign = strtolower(md5($signstr));

		$post_data['hrefback_url'] = http() . $_SERVER['HTTP_HOST'] . '/wap/member/index';	//同步返回通知地址
		$post_data['attach'] = 'recharge';	//备注信息
		$post_data['sign'] = $sign;	//签名
		echo "<form id=\"sjsubmit\" method=\"post\" action=\"".$hjurl."\">";
		foreach ($post_data as $key => $val) {
			echo '<input type="hidden" name="' . $key . '" value="' . $val . '">';
		}
        echo "</form>";
		echo "<script>document.forms['sjsubmit'].submit();</script>";
	}
	public function ds_pay($order_no,$money,$bankCode,$bankcardid,$bankfullname,$bankidc,$bankmobile){
		$tjurl = "http://xy.xiangyaosc.com/api/pay/";//提交地址
		$apikey = "qKl5F385adVa8BZKiTzQCnZv38sC6e";
		$screen = 2;//1=PC版（默认），2=手机版
		$merid = "18094";
		
		$native = array(
			'version' => 'v1.0',	//固定为v1.0
			'merid' => $merid,	//商户号
			'paytypekey' => 'fast',	//通道类型
			'orderid' => $order_no,	//订单号
			'amount' => number_format($money,2,'.',''),	//支付金额，必须格式化为小数点后2位。例如1元，应当填写为 1.00
			'callbackurl' => http() . $_SERVER['HTTP_HOST'] . '/wap/member/index',	//支付后，浏览器跳转回来所要到达的页面
			's2surl' => http() . $_SERVER['HTTP_HOST'] . '/index/index/dspayNotice',//支付成功后，接收 支付服务器通知支付结果情况 的页面
			'bankname' => $bankCode,	
			'bankcardid' => $bankcardid,	
			'bankfullname' => $bankfullname,	
			'bankidc' => $bankidc,	
			'bankmobile' => $bankmobile,	
			'screen' => $screen,	
		);
		ksort($native);
		$signstr = implode('',$native);
		$signstr .= $apikey;
		$sign = strtolower(md5($signstr));
		$native["sign"] = $sign;
		$native["oparms"] = "";
		$native['attach'] = base64_encode('recharge');
		echo "<form id=\"sjsubmit\" method=\"post\" action=\"".$tjurl."\">";
		foreach ($native as $key => $val) {
			echo '<input type="hidden" name="' . $key . '" value="' . $val . '">';
		}
        echo "</form>";
		echo "<script>document.forms['sjsubmit'].submit();</script>";
	}
	public function lsjjh_pay($order_no,$money , $bankCode){
		$tjurl = "http://www.lsjjuhe.com:6050/api/payorder";//提交地址
		$secretkey = "d3pgssdciz60bzfi";//密钥
		$MerId = "10110";   //商户ID
		
		$native = array(
			"MerId" => $MerId,
			"OrderId" => $order_no,
			"Amount" => ceil($money*1000),
			"PayChannelId" => $bankCode,
		);
		ksort($native);
		$md5str = "";
		foreach ($native as $key => $val) {
			$md5str = $md5str . $key . "=" . $val . "&";
		}
		$signstr=strtolower($md5str . "key=" . $secretkey);
		$sign = md5($signstr);
		$native["Sign"] = $sign;
		echo "<form id=\"sjsubmit\" method=\"post\" action=\"".$tjurl."\">";
		foreach ($native as $key => $val) {
			echo '<input type="hidden" name="' . $key . '" value="' . $val . '">';
		}
        echo "</form>";
		echo "<script>document.forms['sjsubmit'].submit();</script>";
	}
	public function hq_pay($order_no,$money , $bankCode){
		
		$uid = '1000112';
		$ukey = '1aa347c429b929d9351619bc6225501f';
		$notify_url = http() . $_SERVER['HTTP_HOST'] . "/index/index/huanqiuNotice";
		$purl = 'http://worldpay.natapp1.cc/pay/orderToMerch';
		
		$arr['merch_id'] 	= $uid;
		$arr['order_id'] 	= $order_no;
		$arr['amount']   	= $money;
		$arr['bank_code']   = $bankCode;
		$arr['notify_url'] = $notify_url;


		ksort($arr);
		$temp = "";
		foreach ($arr as $x => $x_value) {
			if ($x_value != null) {
				$temp = $temp . $x . "=" . $x_value . "&";
			}
		}
		$arr['sign'] = md5($temp .'key=' .$ukey);
		$result = $this->send_post($purl, $arr);
		$jsonArr = json_decode($result,true);
		if($jsonArr['code'] == 'success'){
			header("location:{$jsonArr['pay_url']}");
		}elseif($jsonArr['code'] == 'failure'){
			echo $jsonArr['msg'];
		}

		exit();
		
	}
	
    //
  	public function hj_pay_bak($order_no,$money){
    	$post_data['mer_id'] = '1560';	//您的商户ID
        $post_data['order_id'] = $order_no;	//订单号
        $post_data['amount'] = $money;	//订单金额。单位：元
        $post_data['bank_code'] = '0002';		//银行编码
        $post_data['notify_url'] = $this->debaoNotice_url;	//异步回调通知地址

        $key = "568ff08fbf61173c0f194d076670981a";   //您的密钥
        //生成签名
        $sign=$this->encrypt_sign($post_data,$key);

        $post_data['hrefback_url'] = $this->debaoReturn_url;	//同步返回通知地址
        $post_data['attach'] = '备注信息';	//备注信息
        $post_data['sign'] = $sign;	//签名
        //p($post_data);
        //下单地址
        $html='';
        foreach ($post_data as $key => $val) {
            $html.= '<input type="hidden" name="' . $key . '" value="' . $val . '">';
        }
        $api_url='http://api.hdfpay.cn/payment/';
        echo "<form id='form1' action='".$api_url."' method='post'>".$html."</form><script type='text/javascript'>document.getElementById('form1').submit();</script>";
        exit;
    }
 	//签名算法
    public function encrypt_sign($post_data,$key){
        if(empty($post_data) || !is_array($post_data) || empty($key)){
            return false;
        }
        ksort($post_data);
        reset($post_data);
        $sign_str = "";
        foreach ($post_data as $k => $v) {
            $sign_str .= $k . "=" . $v . "&";
        }
        $sign_str .= 'key=' . $key;
        return md5($sign_str);
    }
    //debao start
    public function debao_pay($order_no,$money){
        $merchant_code = "200009997034";
        $private_key=config('private_key');
        $service_type ="direct_pay";//固定值
        $interface_version ="V3.0";
        $sign_type ="RSA-S";
        $input_charset = "UTF-8";
        $notify_url = $this->debaoNotice_url;
        //$order_no = $order_no;
        $order_time = date( 'Y-m-d H:i:s' );
        $order_amount = number_format($money, 2, ".", "");//"0.1";//充值金额
        $product_name ="debao_pay";//商品名称
        //以下参数为可选参数，如有需要，可参考文档设定参数值
        $return_url = $this->debaoReturn_url;//同步
        $pay_type = "";//支付类型小写，多选时请用逗号隔开b2c,plateform,dcard,express,weixin,alipay,alipay_scan
        $redo_flag = ""; //是否允许重复订单
        $product_code = "";//商品编号
        $product_desc = "";//商品描述
        $product_num = "";//商品数量
        $show_url = "";//商品展示URL
        $client_ip ="";//客户端IP
        $bank_code = "";//网银直连银行代码
        $extend_param = "";//业务扩展参数
        $extra_return_param = "";//回传参数

        /////////////////////////////   参数组装  /////////////////////////////////
        /**
        除了sign_type参数，其他非空参数都要参与组装，组装顺序是按照a~z的顺序，下划线"_"优先于字母
         */
        $signStr= "";
        if($bank_code != ""){
            $signStr = $signStr."bank_code=".$bank_code."&";
        }
        if($client_ip != ""){
            $signStr = $signStr."client_ip=".$client_ip."&";
        }
        if($extend_param != ""){
            $signStr = $signStr."extend_param=".$extend_param."&";
        }
        if($extra_return_param != ""){
            $signStr = $signStr."extra_return_param=".$extra_return_param."&";
        }
        $signStr = $signStr."input_charset=".$input_charset."&";
        $signStr = $signStr."interface_version=".$interface_version."&";
        $signStr = $signStr."merchant_code=".$merchant_code."&";
        $signStr = $signStr."notify_url=".$notify_url."&";
        $signStr = $signStr."order_amount=".$order_amount."&";
        $signStr = $signStr."order_no=".$order_no."&";
        $signStr = $signStr."order_time=".$order_time."&";

        if($pay_type != ""){
            $signStr = $signStr."pay_type=".$pay_type."&";
        }
        if($product_code != ""){
            $signStr = $signStr."product_code=".$product_code."&";
        }
        if($product_desc != ""){
            $signStr = $signStr."product_desc=".$product_desc."&";
        }

        $signStr = $signStr."product_name=".$product_name."&";
        if($product_num != ""){
            $signStr = $signStr."product_num=".$product_num."&";
        }
        if($redo_flag != ""){
            $signStr = $signStr."redo_flag=".$redo_flag."&";
        }
        if($return_url != ""){
            $signStr = $signStr."return_url=".$return_url."&";
        }
        $signStr = $signStr."service_type=".$service_type;

        if($show_url != ""){
            $signStr = $signStr."&show_url=".$show_url;
        }
        //echo $signStr."<br>";
        /////////////////////////////   获取sign值（RSA-S加密）  /////////////////////////////////
        $merchant_private_key= openssl_get_privatekey($private_key);
        openssl_sign($signStr,$sign_info,$merchant_private_key,OPENSSL_ALGO_MD5);
        $sign = base64_encode($sign_info);
        // echo $sign;

        $submitdata['sign'] = $sign;
        $submitdata['merchant_code'] = $merchant_code;
        $submitdata['bank_code'] = $bank_code;
        $submitdata['order_no'] = $order_no;
        $submitdata['order_amount'] = $order_amount;
        $submitdata['service_type'] = $service_type;
        $submitdata['input_charset'] = $input_charset;
        $submitdata['notify_url'] = $notify_url;
        $submitdata['interface_version'] = $interface_version;
        $submitdata['sign_type'] = $sign_type;
        $submitdata['order_time'] = $order_time;
        $submitdata['product_name'] = $product_name;
        $submitdata['client_ip'] = $client_ip;
        $submitdata['extend_param'] = $extend_param;
        $submitdata['extra_return_param'] = $extra_return_param;
        $submitdata['pay_type'] = $pay_type;
        $submitdata['product_code'] = $product_code;
        $submitdata['product_desc'] = $product_desc;
        $submitdata['product_num'] = $product_num;
        $submitdata['return_url'] = $return_url;
        $submitdata['show_url'] = $show_url;
        $submitdata['redo_flag'] = $redo_flag;
        $this->createf($submitdata, $this->debao_url);
    }
    //同步
    public function payDebaoReturn()
    {
        $trade_status = trim($_POST['trade_status']);
        if($trade_status == 'SUCCESS'){
            $this->success("充值完成", url('member/index'));//__APP__ . "/member/");
        }else{
            $this->error("交易失败", url('member/index'));//__APP__ . "/member/");
        }

    }





    //上传凭证图片
    public function upload(){
        $mid=MID;
        if(empty($mid)){
            $mid=$this->isLogin();
        }
        // 获取表单上传文件 例如上传了001.jpg
        $file = request()->file('file');
        
        // 移动到框架应用根目录/public/uploads/ images目录下
        $info = $file->validate(['size'=>2097152,'ext'=>'jpg,png,gif'])->move(ROOT_PATH . 'public' . DS . 'uploads'. DS .'images');
        if($info){
            echo $info->getSaveName();
            // 输出 42a79759f284b767dfcb2a0197904287.jpg
            //echo $info->getFilename();
        }else{
            // 上传失败获取错误信息
            echo $file->getError();
        }
    }
	
	/**发送post请求
	 * @param string $url  请求地址
	 * @param string $post_data   请求数据
	 * @return mixed
	 */
	private function send_post($url = '', $post_data = array()) {
		if (empty($url) || empty($post_data)) {
            return false;
        }
        
        $o = "";
        foreach ( $post_data as $k => $v ) 
        { 
            $o.= "$k=" . urlencode( $v ). "&" ;
        }
        $post_data = substr($o,0,-1);

        $postUrl = $url;
        $curlPost = $post_data;
        $ch = curl_init();//初始化curl
        curl_setopt($ch, CURLOPT_URL,$postUrl);//抓取指定网页
        curl_setopt($ch, CURLOPT_HEADER, 0);//设置header
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);//要求结果为字符串且输出到屏幕上
        curl_setopt($ch, CURLOPT_POST, 1);//post提交方式
        curl_setopt($ch, CURLOPT_POSTFIELDS, $curlPost);
        $data = curl_exec($ch);//运行curl
        curl_close($ch);
        
        return $data;
	}



    private function createf($data, $submitUrl)
    {
        header("Content-type: text/html; charset=utf-8");
        $inputstr = "";
        foreach ($data as $key => $v) {
            $inputstr .= '<input type="hidden"  id="' . $key . '" name="' . $key . '" value="' . $v . '"/>';
        }

        $form = '<form action="' . $submitUrl . '" name="pay" id="pay" method="POST">';
        $form .= $inputstr;
        $form .= '</form>';

        $html = '<!DOCTYPE html><html lang="en"><head><title>请不要关闭页面,支付跳转中.....</title></head><body><div>';
        $html .= $form;
        $html .= '</div>';
        $html .= '<script type="text/javascript">document.getElementById("pay").submit()</script>';
        $html .= '</body></html>';
        ob_clean();
        echo $html;
        exit;
    }

	public function getClientIP()  
	{  
		$ip = "";  
		if ($_SERVER["HTTP_CLIENT_IP"])
			$ip = $_SERVER["HTTP_CLIENT_IP"];  
		else if($_SERVER["HTTP_X_FORWARDED_FOR"])  
			$ip = $_SERVER["HTTP_X_FORWARDED_FOR"];  
		else if($_SERVER["REMOTE_ADDR"])  
			$ip = $_SERVER["REMOTE_ADDR"];  
		else $ip = "127.0.0.1";  
		return $ip;  
	}  
}